package com.fuqi.framework.network.http;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.fuqi.android.zhongcai.application.UniApplication;
import com.fuqi.android.zhongcai.utils.ActivityUtils;
import com.fuqi.framework.application.QuickApplication;
import com.fuqi.framework.utils.NetworkUtils;
import com.fuqi.framework.utils.StringUtils;

public class RequestManager {
    /**
     * Log or request TAG
     */
    public static final String TAG = "VolleyPatterns";
    private static RequestManager instance;

    private RequestQueue mRequestQueue;

    private QuickApplication getApp() {
        return QuickApplication.getInstance();
    }

    private RequestManager() {
        mRequestQueue = Volley.newRequestQueue(getApp());
    }

    public static RequestManager getInstance() {
        if (instance == null)
            instance = new RequestManager();
        return instance;
    }

    public <T> void call(Request<T> request, String tag) {
        // set the default tag if tag is empty
        request.setTag(StringUtils.isEmpty(tag) ? TAG : tag);
        mRequestQueue.add(request);
    }

    public <T> void call(Request<T> request) {
        request.setTag(TAG);
        if (NetworkUtils.isNetworkAvailable(UniApplication.getInstance())) {
            mRequestQueue.add(request);
        } else {
            ActivityUtils.toast("当前网络无连接");
        }
    }

    public void cancel(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }

    public void cancelAll() {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(TAG);
        }
    }
}
